package com.pm.common.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pm.common.WechatService;
import com.pm.common.constant.ProjectConstants;
import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.utils.WeChatUtils;
import com.pm.system.domain.SysConfig;
import com.pm.system.mapper.SysConfigMapper;
import com.pm.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WechatServiceImpl implements WechatService {

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    WeChatUtils weChatUtils;

    @Resource
    SysConfigMapper sysConfigMapper;

    /**
     * 同步企业微信用户ID
     */
    @Override
    public void sysCompanyWechatId() {

        List<SysUser> users = sysUserMapper.selectUserForWechatNull();

        if(!CollectionUtils.isEmpty(users)){
            String token = weChatUtils.getAccessToken();
            for (SysUser user : users) {
                String companyWechatId = weChatUtils.getUserIdByPhone(token,user.getPhonenumber());
                if(StringUtils.isNotBlank(companyWechatId)){
                    SysUser update = new SysUser();
                    update.setUserId(user.getUserId());
                    update.setCompanyWechatId(companyWechatId);
                    sysUserMapper.updateUser(update);
                }
            }
        }

    }

    /**
     * 测试企业微信发送消息功能
     */
    @Override
    public void testMsg() {
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey(ProjectConstants.TEST_WECHAT_NOTICE);
        SysConfig res = sysConfigMapper.selectConfig(sysConfig);
        if(res ==null || StringUtils.isBlank(res.getConfigValue())){
            return ;
        }
        String token = weChatUtils.getAccessToken();
        String[] users = res.getConfigValue().split(",");
        List<String> noticeUsers = Arrays.stream(users).collect(Collectors.toList());
        weChatUtils.sendTextMessage(token,"PM系统测试服务器发送企业微信消息通知!",noticeUsers);
    }
}
